package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Activity;
import cn.wolfcode.domain.ActivityItem;
import cn.wolfcode.domain.Choice;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.service.IActivityItemService;
import cn.wolfcode.service.IActivityService;
import cn.wolfcode.service.IChoiceService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActivityItemService activityItemService;
    @Autowired
    private IChoiceService choiceService;
    @RequestMapping("/list")
    public String list(Model model){
        List<Activity> activities = activityService.listAll();
        model.addAttribute("activities",activities);
        return "/activity/list";
    }

    @RequestMapping("/result")
    public String result(Model model,Long activityId){
        Activity activity = activityService.get(activityId);
        model.addAttribute("activity",activity);
        return "/activity/result";
    }

    @RequestMapping("/show")
    public String show(Long id,Model model){
        //通过id查询出对应的选项信息
        Activity activity = activityService.get(id);
        model.addAttribute("activity",activity);
        return "/activity/show";
    }

    @RequestMapping("/vote")
    @ResponseBody
    public JsonResult vote(Long id,Long activityId){
        //获取到投票选项的id
        //先判断当前用户是否进行了投票
        Choice choice = choiceService.getByActivityId(activityId, UserContext.getCurrentUser().getId());
        //如果choice证明该用户是第一次投票
        if (choice==null){
            //choice中添加一条数据
            Choice cho = new Choice();
            cho.setEmployee(UserContext.getCurrentUser());
            cho.setActivityItem(new ActivityItem(id));
            cho.setCreateTime(new Date());
            choiceService.save(cho);
            //activityItemService中对应的id的num加一
            activityItemService.updateNum(id);
        } else {
            JsonResult result = new JsonResult();
            result.setSuccess(false);
            result.setMsg("该用户已经进行了投票!");
            return result;
        }
        return new JsonResult();
    }
}
